package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.BaseEnum.StateEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.joint.base.entity.Company;
import com.joint.base.entity.FileManage;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.base.util.StringUtils;
import com.joint.core.entity.Knowledge;
import com.joint.core.service.KnowledgeService;
import com.joint.web.action.BaseAdminAction;
import net.sf.json.JSONObject;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dqf on 2015/3/9.
 */
@ParentPackage("com")
public class AjaxKnowledgeAction extends BaseAdminAction {
    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;


    protected Pager pager;

    private Knowledge knowledge;
    private String keyId;
    private String superTypeId;
    private String subTypeId;

    private Dict superType;
    private Dict subType;
    private String title;
    private String context;
    private String contextHtml;
    private String upfileFileName;
    private File upfile;
    private String upfileContentType;
    private String knowledgeId;


    protected List<Knowledge> knowledgeList;
    protected ArrayList<Map<String,Object>> superTypesArrayList;
    protected ArrayList<Map<String,Object>> subTypesArrayList;

    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);
        if(org.apache.commons.lang.StringUtils.isNotEmpty(sidx)&&BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Map<String,Object> params = new HashMap<String,Object>();
        Company company = usersService.getCompanyByUser();
        params.put("company",company);
        params.put("state", new StateEnum[]{StateEnum.Enable});
        params = getSearchFilterParams(_search,params,filters);

        pager = knowledgeService.findByPager(pager, params);


        knowledgeList = (List<Knowledge>) pager.getList();
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(Knowledge knowledge:knowledgeList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",knowledge.getId());
            rMap.put("superType_name",knowledge.getSuperType().getName());
            rMap.put("subType_name",knowledge.getSubType().getName());
            rMap.put("title",knowledge.getName());
            rMap.put("editdate", DataUtil.DateToString(knowledge.getModifyDate()));
            dataRows.add(JSONObject.fromObject(rMap));
        }

        long total =pager.getTotalCount();
        if(total%rows==0){
            total = total/rows;
        }else{
            if(total<rows){
                total = 1;
            }else{
                total = total/rows + 1;
            }
        }
        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);
        data.put("total",total);
        data.put("records",pager.getTotalCount());
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        if(StringUtils.isNotEmpty(keyId)){
            knowledge = knowledgeService.get(keyId);
        }
        return "read";
    }

    public String input(){
        if (StringUtils.isNotEmpty(keyId)){
            knowledge = knowledgeService.get(keyId);
            superType = knowledge.getSuperType();
            subType = knowledge.getSubType();
        }

        Company company = usersService.getCompanyByUser();

        Map<String,Object> rMap=null;
        superTypesArrayList = new ArrayList<Map<String, Object>>();
        for(Dict typeObj:dictService.listFormDefinedEnable(DictBean.DictEnum.SuperKnowledgeType, company.getId())){
            rMap=new HashMap<String, Object>();
            rMap.put("id",typeObj.getId());
            rMap.put("name",typeObj.getName());
            rMap.put("selected","");
            if(knowledge!=null && knowledge.getSuperType()!=null) {
                if(knowledge.getSuperType().getId().equals(typeObj.getId())){
                    rMap.put("selected","selected");
                }
            }
            superTypesArrayList.add(rMap);
        }

        rMap=null;
        subTypesArrayList = new ArrayList<Map<String, Object>>();
        for (Dict typeObj:dictService.listFormDefinedEnable(DictBean.DictEnum.SubKnowledgeType, company.getId())){
            rMap=new HashMap<String, Object>();
            rMap.put("id",typeObj.getId());
            rMap.put("name",typeObj.getName());
            rMap.put("selected","");
            if(knowledge!=null && knowledge.getSuperType()!=null) {
                if(knowledge.getSubType().getId().equals(typeObj.getId())){
                    rMap.put("selected","selected");
                }
            }
            subTypesArrayList.add(rMap);
        }

        return  "input";
    }
    public String infoUpload() throws IOException {
        Company company = usersService.getCompanyByUser();

        Map<String, Object> data = new HashMap<String, Object>();
        if (StringUtils.isNotEmpty(upfileFileName) && upfile != null
                && upfile.length() > 0) {

            FileManage fileManage = gridFSSave(new FileInputStream(upfile),upfileFileName,null,"APPLICATION/OCTET-STREAM",Knowledge.class);

            data.put("state", "SUCCESS");
            data.put("type", ".png");
            data.put("name", upfileFileName);
            data.put("naoriginalNameme", upfileFileName);
            data.put("url", fileManage.getUrl());
            data.put("size", fileManage.getSize());
        }


        return ajaxHtml(JSONObject.fromObject(data).toString());
    }
    public String save(){
        if(StringUtils.isNotEmpty(keyId)){
            knowledge = knowledgeService.get(keyId);
        }else{
            knowledge = new Knowledge();
            knowledge.setCreater(usersService.getLoginInfo());
        }

        if (StringUtils.isNotEmpty(superTypeId)){
            superType = dictService.get(superTypeId);
        }
        if (StringUtils.isNotEmpty(subTypeId)){
            subType = dictService.get(subTypeId);
        }
        if(context.getBytes().length > 600000){
            return ajaxHtmlCallback("404", "对不起，图文信息内容过长！","保存失败");
        }
        knowledge.setKnowledgeId(knowledgeId);
        knowledge.setContext(context);
        knowledge.setContextHtml(contextHtml);
        knowledge.setSubType(subType);
        knowledge.setSuperType(superType);
        knowledge.setName(title);
        knowledge.setState(StateEnum.Enable);
        knowledge.setCompany(usersService.getCompanyByUser());

        if(StringUtils.isNotEmpty(keyId)){
            knowledgeService.update(knowledge);
        }else{
            knowledgeService.save(knowledge);
        }
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    public String delete(){
        if(StringUtils.isEmpty(keyId)){
            return ajaxHtmlCallback("200", "请选择信息！","操作状态");
        }
        Knowledge knowledge = knowledgeService.get(keyId);
        knowledge.setState(StateEnum.Delete);
        knowledgeService.update(knowledge);
        return ajaxHtmlCallback("200", "保存成功！","操作状态");
    }

    @Override
    public Pager getPager() {
        return pager;
    }

    @Override
    public void setPager(Pager pager) {
        this.pager = pager;
    }

    public Knowledge getKnowledge() {
        return knowledge;
    }

    public void setKnowledge(Knowledge knowledge) {
        this.knowledge = knowledge;
    }

    @Override
    public String getKeyId() {
        return keyId;
    }

    @Override
    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    public String getSuperTypeId() {
        return superTypeId;
    }

    public void setSuperTypeId(String superTypeId) {
        this.superTypeId = superTypeId;
    }

    public String getSubTypeId() {
        return subTypeId;
    }

    public void setSubTypeId(String subTypeId) {
        this.subTypeId = subTypeId;
    }

    public Dict getSuperType() {
        return superType;
    }

    public void setSuperType(Dict superType) {
        this.superType = superType;
    }

    public Dict getSubType() {
        return subType;
    }

    public void setSubType(Dict subType) {
        this.subType = subType;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public List<Knowledge> getKnowledgeList() {
        return knowledgeList;
    }

    public void setKnowledgeList(List<Knowledge> knowledgeList) {
        this.knowledgeList = knowledgeList;
    }

    public ArrayList<Map<String, Object>> getSuperTypesArrayList() {
        return superTypesArrayList;
    }

    public void setSuperTypesArrayList(ArrayList<Map<String, Object>> superTypesArrayList) {
        this.superTypesArrayList = superTypesArrayList;
    }

    public ArrayList<Map<String, Object>> getSubTypesArrayList() {
        return subTypesArrayList;
    }

    public void setSubTypesArrayList(ArrayList<Map<String, Object>> subTypesArrayList) {
        this.subTypesArrayList = subTypesArrayList;
    }

    public String getUpfileContentType() {
        return upfileContentType;
    }

    public void setUpfileContentType(String upfileContentType) {
        this.upfileContentType = upfileContentType;
    }

    public File getUpfile() {
        return upfile;
    }

    public void setUpfile(File upfile) {
        this.upfile = upfile;
    }

    public String getUpfileFileName() {
        return upfileFileName;
    }

    public void setUpfileFileName(String upfileFileName) {
        this.upfileFileName = upfileFileName;
    }

    public String getContextHtml() {
        return contextHtml;
    }

    public void setContextHtml(String contextHtml) {
        this.contextHtml = contextHtml;
    }

    public String getKnowledgeId() {
        return knowledgeId;
    }

    public void setKnowledgeId(String knowledgeId) {
        this.knowledgeId = knowledgeId;
    }
}
